﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SearchItem : MonoBehaviour
{

	public Image avatarImage;

	public Text nickText;

	private User _relatedUser;

	private Button _button;

	private AddFriendRequest _addFriendRequest;
	
	/// <summary>
	/// 其所代表的用户
	/// </summary>
	public User RelatedUser
	{
		get { return _relatedUser; }
		set { _relatedUser = value; }
	}


	void Start ()
	{
		//组件初始化
		_button = this.gameObject.GetComponent<Button>();
		_addFriendRequest = UnityFacade.Instance.UiManager.InstantiatedPanelDict[PanelType.SearchFriendPanel]
			.GetComponent<AddFriendRequest>();
		
		//按钮事件函数绑定
		_button.onClick.AddListener(delegate { SearchItemClicked(); });
	}
	
	// Update is called once per frame
	void Update () {
		
	}
	
	/// <summary>
	/// 刷新展示（根据所代表的User）
	/// </summary>
	public void SyncShow()
	{
		nickText.text = _relatedUser.Nick;
		//todo 之后处理image
		HttpTool.Instance.GetImageConvertToSpriteByURL(_relatedUser.Avatar,"opponent");
		StartCoroutine(SetSpriteToImage());
	}

	private void SearchItemClicked()
	{
		Debug.Log("发送好友请求");
		// 发送添加好友请求
		_addFriendRequest.SendRequest(_relatedUser.UserId);
		
	}
	
	// Use this for initialization
	
	private IEnumerator SetSpriteToImage()
	{
		//todo 可以开启一个等待动画的显示
        
		while (HttpTool.Instance.OpponentSprite == null)
		{
			yield return new WaitForFixedUpdate();
		}
		avatarImage.sprite = HttpTool.Instance.OpponentSprite;
		//置为null，待下一次处理
		HttpTool.Instance.ClearSprite("opponent");
       
	}
	
}
